﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace DNA
{
    class user_atr: tree
    {
        string[,] _way_atr;
       int _help_way_atr = 0;//указатель на массив движения в дереве
        int[] _what_we_use = new int[50];//массив, в котором уже использованные атрибуты
         int _help_what_we_use = 0;//указатель для массива использованных атрибутоv
         int _min_yarv;
         decimal _znach;
         int _count_yrav = 0;
        int help_in_tab = 0;
        int _Y;


       public void Coral_tree()//начало заполнения и проведения дерева по корреляционным данным
        {
            
           _Y = find_me_y();
            _way_atr = new string[40, 3];
            _min_yarv = Convert.ToInt32(min_yrav_corel.Value);
            regres_for_tree reg = new regres_for_tree();
            tree tr = this.Owner as tree;
            reg.Owner = tr;
            int koren = reg.new_main_koren(tr.Y.SelectedItem.ToString());
            {
                _way_atr[_help_way_atr, 0] = koren.ToString();
                Count_way(koren, true, false);
                _what_we_use[_help_what_we_use] = koren;//добавляем корень в список уже использованных атрибутов
                _help_what_we_use++;
                _help_way_atr++;
                build_tree(koren);//переходим к дальнейшему построению дерева 

            }
            for (int i = 0; i < data.Rows.Count; i++)
            {
                {
                    for (int stolbech = 0; stolbech < tr.data.Columns.Count; stolbech++)
                        tr.data[stolbech, i].Style.BackColor = Color.White;
                }

            }
        }

        public void build_tree(int nah_koren)
        {
            int nah_new_yzel = 0;
            goto again;
           // decimal veroat;
           // tree tr = this.Owner as tree;
        again:
            {
                tree tr = this.Owner as tree;    
                 bool we_buit_corel = tr.tree_corel.Checked;    
                 if (we_buit_corel == true) nah_new_yzel = new_yzel(nah_koren);//опеределяем следующий узел
                else nah_new_yzel = new_yzel_standart(nah_koren);
                if (nah_new_yzel < anti_chikl)
                {
                    _what_we_use[_help_what_we_use] = nah_new_yzel;//заносим его в список использованных
                    _help_what_we_use++;
                    Count_way(nah_new_yzel, false, false);//расчитываем возможности дальнейшего разбиения
                    _help_way_atr++;
                    if (proverka_yzla_na_list(nah_new_yzel) != true)//проверяем, не конец ли это
                    {//если нет, то заносим дан5ные в таблицу и повторяем данный алгоритм...тем самым, мы всегда двигаемся влево
                    //    veroat = veroiatnost(nah_new_yzel);
                        nah_koren = nah_new_yzel;                      
                        goto again;
                    }
                    else
                    {
                        //ЗДЕСЬ Я ВОЗДВИГНУ ФЛАГ НЕБИТОТВОРНЫЙ!
                        for (int ro = 0; ro <= tr.set_value.Rows.Count - 1; ro++)
                        {
                            if (tr.data.Columns[Convert.ToInt32(_way_atr[_help_way_atr-1, 0])].HeaderText == Convert.ToString(tr.set_value[0, ro].Value))
                            {
                                if (Convert.ToString(tr.set_value[1, ro].Value) != "")
                                {
                                    tr.VEROIATNOST = veroiatnost(nah_new_yzel);
                                }
                                else
                                {
                                    _way_atr[_help_way_atr - 1, 0] = null;
                                    _way_atr[_help_way_atr - 1, 1] = null;
                                    _way_atr[_help_way_atr - 1, 2] = null;
                                    _help_way_atr--;
                                    goto List;
                                }
                                break;      
                            }
                        }
                               
                       
                    }
                }
            }
        List:
            {
                if (_way_atr[_help_way_atr - 1, 2] != "#")
                {
                    _way_atr[_help_way_atr - 1, 1] = _way_atr[_help_way_atr - 1, 2];
                    _way_atr[_help_way_atr - 1, 2] = "#";
                    nah_koren = Convert.ToInt32(_way_atr[_help_way_atr - 1, 0]);
                    goto again;
                }
                else
                {
                    _way_atr[_help_way_atr - 1, 0] = null;
                    _way_atr[_help_way_atr - 1, 1] = null;
                    _way_atr[_help_way_atr - 1, 2] = null;
                    _help_way_atr--;
                    if (_help_way_atr == 1)
                    {
                        while (_help_what_we_use != 2)
                        {
                            _what_we_use[_help_what_we_use - 1] = 150;
                            _help_what_we_use--;
                        }
                       }
                    if (_help_way_atr == 0) { }//goto Break;}
                    else goto List;
                }
            }
            //Break: { }
        }

        public bool proverka_yzla_na_list(int koren)//проверяем, не лист ли у нас получился...лист - когда в узле не более 5 уравнений
        {
            tree tr = this.Owner as tree;
            bool answer = false;
            _count_yrav = 0;
            bool firrst = true;
            for (int whu = 0; whu <= _help_way_atr - 1; whu++)
            {
                if (firrst == true)
                {
                    pokraska((Convert.ToInt32(_way_atr[whu, 0])), whu, true, false);
                    firrst = false;
                }
                else pokraska((Convert.ToInt32(_way_atr[whu, 0])), whu, false, false);
            }
            for (int row = 0; row < tr.data.Rows.Count; row++)
            {
                if (tr.data[koren, row].Style.BackColor == Color.Yellow)
                {
                    _count_yrav++;
                }
            }
            if (_count_yrav <= _min_yarv) answer = true;
            pokraska(0, 0, false, true);
            return answer;
        }

      bool if_we_use_twice(int verhina)//проверям, не использовали мы данный атрибут раньше
        {
            bool answ = false;
            for (int i = 0; i < _help_what_we_use; i++)
            {
                if (_what_we_use[i] == verhina)
                {
                    answ = true;
                    break;
                }
            }
            return answ;
        }

        public int new_yzel_standart(int koren)
        {
            int new_koren = 0;
            tree tr = this.Owner as tree;
            help_in_tab = 0;
            tr.calcdata.Rows.Clear();
            int max1, max2, verh;
            bool cheng = false;
            for (int pretendent = 0; pretendent < tr.data.Columns.Count; pretendent++)
            {
                if (tr.data.Columns[pretendent].HeaderText == "Диагноз") continue;
                if (if_we_use_twice(pretendent) == true) continue;
                tr.calcdata.Rows.Add();
                tr.calcdata[0, help_in_tab].Value = pretendent;
                Count_way(pretendent, false, true);
                help_in_tab++;
            }

            // max1 = Convert.ToInt32(calcdata[1, 0].Value.ToString());
            // max2 = Convert.ToInt32(calcdata[2, 0].Value.ToString());
            // verh = Convert.ToInt32(calcdata[0, 0].Value.ToString());
            max1 = 1;
            max2 = 1;
            verh = 0;
            for (int row = 0; row < tr.calcdata.Rows.Count - 1; row++)
            {
                try
                {
                    if ((max1 > Convert.ToInt32(tr.calcdata[1, row].Value.ToString())) && (max2 > Convert.ToInt32(tr.calcdata[2, row].Value.ToString()))) continue;
                    if (((max2 * max1) > (Convert.ToInt32(tr.calcdata[1, row].Value.ToString()) * Convert.ToInt32(tr.calcdata[2, row].Value.ToString()))) && (Convert.ToInt32(tr.calcdata[1, row].Value.ToString()) / max1 < 2) && (Convert.ToInt32(tr.calcdata[2, row].Value.ToString()) / max2 < 2)) continue;
                    if ((Convert.ToInt32(tr.calcdata[1, row].Value.ToString()) / max1 < 2) && (Convert.ToInt32(tr.calcdata[2, row].Value.ToString()) / max2 < 2)) continue;
                    max1 = Convert.ToInt32(tr.calcdata[1, row].Value.ToString());
                    max2 = Convert.ToInt32(tr.calcdata[2, row].Value.ToString());
                    verh = Convert.ToInt32(tr.calcdata[0, row].Value.ToString());
                    cheng = true;
                }
                catch
                {
                    continue;
                }
            }
            if (cheng == true)
            {
                new_koren = verh;
                _way_atr[_help_way_atr, 0] = new_koren.ToString();

            }
            else new_koren = anti_chikl;
            return new_koren;
        }

        public int new_yzel(int koren)//находим новый узел (определяем следующий рассматриваемый атрибут)
        {
            int atr = 0;
            string att = "";
            int stet4ik = 0;
            decimal korel = 0;
            decimal niz_gran;
            tree tr = this.Owner as tree;
            niz_gran = Convert.ToDecimal(corel_niz.SelectedItem);
            for (int row = 0; row < tr.calc_data.Rows.Count - 1; row++)
            {
                if (tr.calc_data[0, row].Value.ToString() == koren.ToString())
                {
                    stet4ik = row + 1;
                    att = tr.calc_data[1, row].Value.ToString();
                    try
                    {
                        korel = Convert.ToDecimal(tr.calc_data[2, row].Value.ToString());
                    }
                    catch
                    { continue; }
                    try
                    {
                        while (tr.calc_data[0, stet4ik].Value.ToString() == koren.ToString())
                        {

                            if ((Convert.ToDecimal(tr.calc_data[2, stet4ik].Value.ToString())) > korel)
                            {
                                if ((if_we_use_twice(Convert.ToInt32(tr.calc_data[1, stet4ik].Value.ToString()))) == true)  //чтобы не использовали атрибут дважды
                                {
                                    stet4ik++;
                                    if (stet4ik > (tr.calc_data.Rows.Count - 1)) goto Move_forvard;
                                    else continue;
                                }
                                atr = Convert.ToInt32(tr.calc_data[1, stet4ik].Value.ToString());
                                korel = Convert.ToDecimal(tr.calc_data[2, stet4ik].Value.ToString());
                                stet4ik++;
                                if (stet4ik > (tr.calc_data.Rows.Count - 1)) goto Move_forvard;
                            }
                            else
                            {
                                stet4ik++;
                                if (stet4ik > (tr.calc_data.Rows.Count - 1)) goto Move_forvard;
                            }
                        }
                    }
                    catch
                    {
                        goto Move_forvard;
                    }

                    break;
                }
                else
                { if (stet4ik++ > (tr.calc_data.Rows.Count - 1)) goto Move_forvard; }
            }
            goto Move_forvard;
        Move_forvard:
            if (atr == 0)
            {
                atr = anti_chikl;
                return Convert.ToInt32(atr);
            }
            _znach = korel;

            if (_znach <= niz_gran)
            {
                atr = anti_chikl;
                return Convert.ToInt32(atr);
            }
            else
            {
                _way_atr[_help_way_atr, 0] = atr.ToString();//заносим новый узел в массив движения в дереве
                return Convert.ToInt32(atr);
            }
        }


        public void pokraska(int koren, int way__atr, bool first, bool all_white)
        {
            tree tr = this.Owner as tree;
            if (first == true)
            {
                for (int i = 0; i < Convert.ToInt32(tr.eq_count.Value); i++)
                {
                    if (Convert.ToString(tr.data[koren, i].Value) == _way_atr[way__atr, 1])
                    {
                        for (int stolbech = 0; stolbech < tr.data.Columns.Count; stolbech++)
                            tr.data[stolbech, i].Style.BackColor = Color.Yellow;
                    }
                }
            }
            if (first == false)
            {
                for (int i = 0; i < Convert.ToInt32(tr.eq_count.Value); i++)
                {
                    if (Convert.ToString(tr.data[koren, i].Value) == _way_atr[way__atr, 1])
                    {
                        if (tr.data[koren, i].Style.BackColor == Color.Yellow)
                            continue;
                    }
                    else
                    {
                        if (tr.data[koren, i].Style.BackColor == Color.Yellow)
                        {
                            for (int stolbech = 0; stolbech < tr.data.Columns.Count; stolbech++)
                            {
                                tr.data[stolbech, i].Style.BackColor = Color.White;
                            }
                        }
                    }
                }
            }
            if (all_white == true)
            {
                for (int i = 0; i < Convert.ToInt32(tr.eq_count.Value); i++)
                {
                    for (int j = 0; j < tr.data.Columns.Count; j++)
                    {
                        tr.data[j, i].Style.BackColor = Color.White;
                    }
                }
            }

        }

        public decimal veroiatnost(int koren_v)
        {
            decimal veroatnost = 1;
            int chislitel = 0;
            bool first = true;
            tree tr = this.Owner as tree;
            int ro = tr.data.Rows.Count - 1;
            for (int whu = 0; whu <= _help_way_atr - 1; whu++)
            {
                if (first == true)
                {
                    pokraska((Convert.ToInt32(_way_atr[whu, 0])), whu, true, false);
                    first = false;
                    for (int row = 0; row < tr.data.Rows.Count; row++)
                    {
                        if (tr.data[koren_v, row].Style.BackColor == Color.Yellow)
                        {
                            if (il.Checked == true)
                            {
                                if (Convert.ToString(tr.data[_Y, row].Value) == "полож") chislitel++;
                            }
                            else
                            {
                                if (Convert.ToString(tr.data[_Y, row].Value) == "отрицат") chislitel++;
                            }
                        }
                    }
                    veroatnost = ((decimal)chislitel / (decimal)ro);
                    chislitel = 0;
                }
                else
                {
                    pokraska((Convert.ToInt32(_way_atr[whu, 0])), whu, false, false);
                    for (int row = 0; row < tr.data.Rows.Count; row++)
                    {
                        if (tr.data[koren_v, row].Style.BackColor == Color.Yellow)
                        {
                            if (il.Checked == true)
                            {
                                if (Convert.ToString(tr.data[_Y, row].Value) == "полож") chislitel++;
                            }
                            else
                            {
                                if (Convert.ToString(tr.data[_Y, row].Value) == "отрицат") chislitel++;
                            }
                        }
                    }
                    veroatnost = veroatnost * (((decimal)chislitel / (decimal)ro));
                    chislitel = 0;
                }
            }
            pokraska(0, 0, false, true);
            return veroatnost;
        }

      int find_me_y()
        {
            tree tr = this.Owner as tree;  
          int _Y = 0;
            for (int i = 0; i < tr.data.Columns.Count; i++)
            {
                if (tr.data.Columns[i].HeaderText == tr.Y.SelectedItem.ToString()) { _Y = i; break; }
            }
            return _Y;
        }

      void Count_way(int who_koren, bool first, bool standart)
        {
            string result = "";
            int co;
            int wa1 = 0;
            int wa2 = 0;
            int ya1 = 0;
            int ya2 = 0;
            bool flag = false;
            int help_count = 0;
            string[,] count = new string[10, 2];
            bool firrst = true;
            if (first != true)
            {
                for (int whu = 0; whu < _help_way_atr; whu++)
                {
                    if (firrst == true)
                    {
                        pokraska((Convert.ToInt32(_way_atr[whu, 0])), whu, true, false);
                        firrst = false;
                    }
                    else pokraska((Convert.ToInt32(_way_atr[whu, 0])), whu, false, false);
                }
            }
            tree tr = this.Owner as tree;
            for (int i = 0; i < Convert.ToInt32(tr.eq_count.Value); i++)
            {
                if (Convert.ToString(tr.data[who_koren, i].Value) == "") break;
                if (first != true)
                {
                    if (tr.data[who_koren, i].Style.BackColor != Color.Yellow) continue;
                }

                for (int j = 0; j < 10; j++)
                {
                    if (count[j, 0] == Convert.ToString(tr.data[who_koren, i].Value))
                    {
                        help_count = Convert.ToInt32(count[j, 1]);

                        help_count++;
                        count[j, 1] = help_count.ToString();
                        flag = true;//для того, чтобы у нас повторно значение атрибуты не было добавленно в массив
                        break;
                    }
                }
                if (flag != true)
                {
                    for (int j = 0; j < 10; j++)
                    {
                        help_count = 0;
                        if (count[j, 0] == null)
                        {

                            count[j, 0] = Convert.ToString(tr.data[who_koren, i].Value);
                            help_count++;
                            count[j, 1] = help_count.ToString();
                            break;

                        }
                    }
                }
                flag = false;
            }
            for (int i = 0; i < 10; i++)
            {
                if (count[i, 0] != null)
                {
                    wa1++;
                }
                else break;
            }
            if (wa1 == 1)
            {
                result = count[0, 0] + " || " + "#";
                _way_atr[_help_way_atr, 1] = count[0, 0];
                _way_atr[_help_way_atr, 2] = "#";
                tr.calcdata[1, help_in_tab].Value = count[0, 1];
                tr.calcdata[2, help_in_tab].Value = 0;

            }
            if (wa1 == 2)
            {
                result = count[0, 0] + " || " + count[1, 0];
                _way_atr[_help_way_atr, 1] = count[0, 0];
                _way_atr[_help_way_atr, 2] = count[1, 0];
                tr.calcdata[1, help_in_tab].Value = count[0, 1];
                tr.calcdata[2, help_in_tab].Value = count[1, 1];
            }
            if (wa1 > 2)
            {
                wa1 = Convert.ToInt32(count[0, 1]);
                wa2 = 0;
                ya1 = Convert.ToInt32(count[0, 1]);
                ya1 = 0;
                for (int i = 1; i < 10; i++)
                {
                    if (wa1 < Convert.ToInt32(count[i, 1]))
                    {
                        wa1 = Convert.ToInt32(count[i, 1]);
                        wa2 = i;
                    }
                }
                for (int i = 0; i < 10; i++)
                {
                    if (ya1 < Convert.ToInt32(count[i, 1]) && Convert.ToInt32(count[i, 1]) < wa1)
                    {
                        ya1 = Convert.ToInt32(count[i, 1]);
                        ya2 = i;
                    }
                }
            }
                if (standart == true)
                {
                    tr.calcdata[1, help_in_tab].Value = count[wa2, 1];
                    tr.calcdata[2, help_in_tab].Value = count[ya2, 1];
                }
                else
                {
                   // result = count[wa2, 0] + " || " + count[ya2, 0];
                    //_way_atr[_help_way_atr, 1] = count[wa2, 0];
                    //_way_atr[_help_way_atr, 2] = count[ya2, 0];
                    for (int ro = 0; ro <= tr.set_value.Rows.Count - 1; ro++)
                    {
                         co = Convert.ToInt32(_way_atr[_help_way_atr, 0]);
                        if (tr.data.Columns[co].HeaderText == Convert.ToString(tr.set_value[0, ro].Value))
                        {
                            if (Convert.ToString(tr.set_value[1, ro].Value) == "")
                            {
                                _way_atr[_help_way_atr, 1] = count[wa2, 0];
                                _way_atr[_help_way_atr, 2] = count[ya2, 0];
                                break;
                            }
                            if (Convert.ToString(tr.set_value[1, ro].Value) == count[wa2, 0])
                            {
                                _way_atr[_help_way_atr, 1] = count[wa2, 0];
                                _way_atr[_help_way_atr, 2] = "#";
                                break;
                            }
                            if (Convert.ToString(tr.set_value[1, ro].Value) == count[ya2, 0])
                            {
                                _way_atr[_help_way_atr, 1] = count[ya2, 0];
                                _way_atr[_help_way_atr, 2] = "#";
                                break;
                            }
                        }
                    }
                   
                }
            
          
            pokraska(0, 0, false, true);
            //return result;
        }
    
    }
}
